import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as stats
from matplotlib import rcParams
from matplotlib.colors import LogNorm


rcParams['font.sans-serif'] = ['SimHei']  # 中文为宋体
rcParams['font.serif'] = ['Times New Roman']  # 英文为新罗马
rcParams['axes.unicode_minus'] = False  # 正常显示负号
rcParams['font.size'] = 15  # 设置字号

df = pd.read_csv('E:\江苏移动-hzy工作资料\\5GC学习资料\\01-中兴5GC资料\python-tasks\plot-corr\data-test.csv')
df['日期']=pd.to_datetime(df['日期'])
df.set_index(df['日期'],drop=True,inplace=True)
df.drop(columns=['日期'],inplace=True)



#法1：Scipy计算出的得分--
r, p = stats.pearsonr(df.dropna()['蜜汁焗餐包'], df.dropna()['铁板酸菜豆腐'])
print(f"Scipy computed Pearson r: {r} and p-value: {p}")
# 输出：使用 Scipy 计算皮尔逊相关结果的 r 值：0.20587745135619354，以及 p-value：3.7902989479463397e-51



#法2：Pandas计算出的得分--
overall_pearson_r = df.corr().iloc[0, 1]  #计算单列的person相关性
print(f"Pandas computed Pearson r: {overall_pearson_r}")
# 输出：使用 Pandas 计算皮尔逊相关结果的 r 值：0.2058774513561943

df.corr() #计算每一列之间的person相关性
df.corr(method='spearman')
df.corr(method='kendall')




# 计算滑动窗口同步性--中位数（中值滤波）
f, ax = plt.subplots(figsize=(17, 13))
df.rolling(window=5, center=True).median().plot(ax=ax) #前后5个数据的中位值
ax.set(xlabel='Time', ylabel='Pearson r')
ax.set(title=f"Overall Pearson r = {np.round(overall_pearson_r,  2)}")
plt.show()



# 设置窗口宽度，以计算滑动窗口同步性
r_window_size = 8
# 插入缺失值
df_interpolated = df.interpolate()
# 计算滑动窗口同步性(每一行的person相关性得分)
rolling_r = df_interpolated['蜜汁焗餐包'].rolling(window=r_window_size, center=True).corr(df_interpolated['铁板酸菜豆腐'])

f,ax=plt.subplots(2,1,figsize=(16,8),sharex=True)


df[['蜜汁焗餐包','铁板酸菜豆腐']].rolling(window=5,center=True).median().plot(ax=ax[0])
ax[0].set(xlabel='Frame',ylabel='Smiling Evidence')
ax[0].grid(linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层

rolling_r.plot(ax=ax[1])
ax[1].set(xlabel='Frame',ylabel='Pearson r')
ax[1].grid(linestyle='--',linewidth=0.5,color='gray',zorder=0)#zorder=0标识置于底层

plt.suptitle("Smiling data and rolling window correlation")
plt.show()


#####################################################################################
#####################################################################################
#####################################################################################
#相关性分析的热力图表示
fig=plt.figure(figsize=(10, 8), dpi=300,constrained_layout=True)  # 可以自动调整图表之间的距离大小
spec=plt.GridSpec(1,1,figure=fig)
ax_main = fig.add_subplot(spec[:, :])
# df.corr() #计算每一列之间的person相关性
# df.corr(method='spearman')
# df.corr(method='kendall')
# cfm_plot = sns.heatmap(matrix, ax=ax_main, fmt= "" , norm=LogNorm(), linewidths= 0.5 , linecolor= "grey" , cmap= "crest" )

cfm_plot=sns.heatmap(df.corr()[::-1], ax=ax_main, annot=True, vmax=1, square=True, cmap="Blues")
plt.setp(ax_main.yaxis.get_majorticklabels(), rotation=0)

plt.title('相关性热力图')
plt.show()


